#!/usr/bin/python3

#  Copyright (C) 2013 Hai Bison
#
#  See the file LICENSE at the root directory of this project for copying
#  permission.

'''
This tool builds the project and copies output ``.jar`` to ``bin`` directory.
'''

import argparse, os, re, subprocess, sys, zipfile
from subprocess import CalledProcessError

parser = argparse.ArgumentParser(
    description='''Builds the project and copies output `.jar` to `bin`
                directory.''')
parser.add_argument('-s', '--snapshot', action='store_true',
    help='''if set, append to the end of the file name current revision number.
         ''')
parser.add_argument('-D', '--debug', action='store_true',
    help='''if set, use DEBUG mode instead of RELEASE.''')

ARGS = parser.parse_args()

SRC_DIR = os.path.dirname(os.path.abspath(sys.argv[0]))

# SNAPSHOT
revision = None
if ARGS.snapshot:
    revision = subprocess.check_output(['hg', 'log', '-l', '1', SRC_DIR])
    revision = re.search(b'(?sm)^changeset:[ \t]+[0-9]+:[0-9a-f]+$', revision)
    if revision:
        revision = re.search(b':[ \t]+[0-9]+:', revision.group()).\
                   group()[1:-1].strip()

# LIB NAME AND VERSION
filename = os.sep.join([SRC_DIR, 'code', 'src', 'com', 'haibison', 'android',
                        'hutieu', 'Sys.java'])
with open(filename, 'r') as f:
    DATA = f.read()
    _ = re.search(r'(?s)LIB_CODE_NAME = ".+?";', DATA).group()
    lib_name = re.search(r'".+"', _).group()[1:-1]
    _ = re.search(r'(?s)LIB_VERSION_NAME = ".+?";', DATA).group()
    version = re.search(r'".+"', _).group()[1:-1].replace(' ', '_')

# BUILD THE PROJECT
os.chdir(os.path.join(SRC_DIR, 'code'))
try:
    if ARGS.debug: print(' > Using DEBUG mode')
    subprocess.check_output(['ant', 'clean',
                             'debug' if ARGS.debug else 'release'])
except CalledProcessError as e:
    print(' ! Error building project:\n\t')
    print(e.output.replace(b'\n', b'\n\t').decode().strip())
    sys.exit(1)

# CHECK FOR OUTPUT `classes.jar`
file_classes_jar = os.sep.join([SRC_DIR, 'code', 'bin', 'classes.jar'])
if not os.path.isfile(file_classes_jar):
    print(' ! Can\'t find "{}"'.format(os.path.basename(file_classes_jar)))
    sys.exit(1)
if not zipfile.is_zipfile(file_classes_jar):
    print(' ! Invalid "{}"'.format(os.path.basename(file_classes_jar)))
    sys.exit(1)

# MOVE `classes.jar` TO `bin`
if revision: revision = '_r{}'.format(revision)
filename = '{}_v{}{}{}.jar'.format(lib_name, version,
                                   revision if revision else '',
                                   '_DEBUG' if ARGS.debug else '')
filename = os.sep.join([SRC_DIR, 'bin', filename])
if subprocess.call(['mv', file_classes_jar, filename]):
    print(' ! Can\'t move "{}" to "{}"'.format(
          os.path.relpath(file_classes_jar, SRC_DIR),
          os.path.relpath(filename, SRC_DIR)))
else:
    print(' > DONE >> "{}"'.format(os.path.relpath(filename, SRC_DIR)))